<template>
	<div class="orderDetails">
    <!-- 实销上报明细/编辑 -->
    <div :style="{
        'margin-top': '20px',
        border: '1px solid #f2f2f2'
      }">
      <div :style="{
          'background':' #f2f2f2',
          'height': '32px',
          'line-height': '32px',
          'padding-left': '20px',
          'margin-bottom': '20px',
        }">车辆基本信息</div>
      <FormPanel
        ref="formPanelA"
        :list="formList"
        :cols="4"
        labelWidth='100'
        :isSubmitBtn="false"
        :formType="'show'"
      />
    </div>
    <div :style="{
        'margin-top': '20px',
        border: '1px solid #f2f2f2'
      }">
      <div :style="{
          'background':' #f2f2f2',
          'height': '32px',
          'line-height': '32px',
          'padding-left': '20px',
          'margin-bottom': '20px',
        }">客户信息</div>
      <FormPanel
        ref="formPanelB"
        :list="formList1"
        :cols="4"
        labelWidth='100'
        :isSubmitBtn="false"
        :formType="'show'"
      />
    </div>
    <div :style="{
        'margin': '20px 0 60px 0',
        border: '1px solid #f2f2f2'
      }">
      <div :style="{
          'background':' #f2f2f2',
          'height': '32px',
          'line-height': '32px',
          'padding-left': '20px',
          'margin-bottom': '20px',
        }">发票信息</div>
      <FormPanel
        ref="formPanelC"
        :list="formList2"
        :cols="4"
        labelWidth='100'
        :isSubmitBtn="false"
        :formType="type"
        @formChange="formChangeHandle"
      />
    </div>
		<div class="upWard" :style="{
        position: 'absolute',
        left: 0,
        bottom: 0,
        right: 0,
        zIndex: 9,
        borderTop: '1px solid #e9e9e9',
        padding: '10px 20px',
        background: '#fff',
        textAlign: 'right'
      }">
      <el-button size="small" v-if="type!=='show'" type="primary" @click="saveFunc">保存</el-button>
			<el-button size="small" @click="closeDialog">返回</el-button>
		</div>
     <!-- 开票人信息选择 -->
    <BaseDialog
      :visible.sync="visibleCustomer"
      title="开票人信息选择"
      destroyOnClose
      :containerStyle="{height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px'}"
    >
      <selectCustomer @close="closeCustomerDialog" />
    </BaseDialog>
	</div>
</template>

<script>
import { getReportOrderDetails, updateSalesOrderInvoice } from '@/api/retail/salesmanage/solidReport';
import selectCustomer from '../salesordermanage/selectCustomer'
import moment from 'moment'
import { dictionary } from '@/utils/dictMixin';
import { notifyAction } from '@/utils';
export default {
  name: 'orderDetails',
  mixins: [dictionary],
  props: {
    type: {
      type: String,
      default: 'show'
    },
    rowData : {
      type: Object,
      default: () => ({})
    }
  },
  components: {
    selectCustomer
  },
	data (){
		return {
      formList: this.createFormList(),
      formList1: this.createFormList1(),
      formList2: this.createFormList2(),
      whiteListOfFieldName: [
        'invoiceDate'
      ],
      orginData: '',
      selectCustomerId: null,
      visibleCustomer: false
		}
  },
  mounted (){
    this.init();
  },
	methods: {
    init (){
      // console.log(this.type)
      // console.log(this.rowData)
      this.reportOrderDetail(this.rowData);
    },
    async reportOrderDetail (row){  //根据父组件传递的ID获取详细数据并赋值
      let { preDateHandler } = this
      let res = await getReportOrderDetails(row.soVinId);
      this.orginData = res.data;
  		if(res.resultCode == 200){
        this.selectCustomerId = res.data['customerId']
        this.formList.forEach(x => {
          if (this.whiteListOfFieldName.includes(x.fieldName)) {
            let date = res.data[x.fieldName];
            x.initialValue = preDateHandler(date)
          }else{
            x.initialValue = res.data[x.fieldName];
          }
        });
        this.formList1.forEach(x => {
          if (this.whiteListOfFieldName.includes(x.fieldName)) {
            let date = res.data[x.fieldName];
            x.initialValue = preDateHandler(date)
          }else{
            x.initialValue = res.data[x.fieldName];
          }
        });
        this.formList2.forEach(x => {
          if (this.whiteListOfFieldName.includes(x.fieldName)) {
            let date = res.data[x.fieldName];
            x.initialValue = preDateHandler(date)
          } else if (x.fieldName === 'invoiceUrl') {
            try{
              let urls = res.data['invoiceUrl'].split(',')
              let urlsList = urls.map(item => {
                let origin = item.split('/');
                let fileName = origin[origin.length-1];
                return { name: fileName, url: item};
              });
              x.initialValue.push(...urlsList)
            }catch(e){}
          } else if (x.fieldName === 'invoiceCustomer') {
            x.initialValue = res.data['customerName']
          } else {
            x.initialValue = res.data[x.fieldName];
          }
        });
      }
    },
		createFormList () {
			return [
				{
          type: 'INPUT',
          label: '品牌',
          fieldName: 'brandName',
          initialValue: ''
        },
        {
          type: 'INPUT',
          label: '车系,',
          fieldName: 'seriesName',
          initialValue: ''
        },
        {
          type: 'INPUT',
          label: '车型',
          fieldName: 'modelName',
          initialValue: ''
        },
        {
          type: 'INPUT',
          label: '配置',
          fieldName: 'packageName',
          initialValue: ''
        },
        {
          type: 'INPUT',
          label: '颜色',
          fieldName: 'colorName',
          initialValue: ''
        },
        {
          type: 'INPUT',
          label: 'VIN号',
          fieldName: 'vin',
          initialValue: ''
        },
			]
    },
    createFormList1 () {
			return [
        // 车辆库存信息
        {
          type: 'INPUT',
          label: '销售订单号',
          fieldName: 'viNo',
          placeholder: '',
          initialValue: ''
        },
        {
          type: 'INPUT',
          label: '客户编号',
          fieldName: 'customerNo',
          placeholder: '',
          initialValue: '',
        },
        {
          type: 'INPUT',
          label: '客户名称',
          fieldName: 'customerName',
          placeholder: '',
          initialValue: '',
        },
        {
          type: 'SELECT',
          label: '性别',
          fieldName: 'gender',
          initialValue: '',
          placeholder: '',
          itemList: this.createDictList('1002'),
        },
        {
          type: 'INPUT',
          label: '手机号码',
          fieldName: 'mobilePhone',
          initialValue: '',
          placeholder: '',
        },
        {
          type: 'SELECT',
          label: '证件类型',
          fieldName: 'ctCode',
          initialValue: '',
          placeholder: '',
          itemList: this.createDictList('1508'), // 原'1058'修改为'7035' 再改为'1508'
        },
        {
          type: 'INPUT',
          label: '证件号码',
          fieldName: 'certificateNo',
          initialValue: '',
          placeholder: '',
        },
        {
          type: 'SELECT',
          label: '购车用途',
          fieldName: 'vehiclePurpose',
          initialValue: '',
          placeholder: '',
          itemList: this.createDictList('1511')
        },
        {
          type: 'INPUT',
          label: '地址',
          fieldName: 'address',
          initialValue: '',
          placeholder: '',
          selfCols: 2,
        },
			]
    },
    createFormList2 () {
			return [
        {
          type: 'INPUT',
          label: '合同编号',
          fieldName: 'contractNo',
          disabled: true,
          initialValue: '',
          placeholder: '',
        },
        {
          type: 'INPUT',
          label: '开票人',
          fieldName: 'transactor',
          initialValue: '',
          rules: this.type!=='show'?[{ required: true, message: '请填写开票人', trigger: 'blur' }]:'',
          placeholder: '',
        },
        // 'invoiceMobile' 以后版本需要
        // {
        //   type: 'INPUT',
        //   label: '手机号',
        //   fieldName: 'invoiceMobile',
        //   initialValue: '',
        //   rules: this.type!=='show'?[{ required: true, message: '请填写手机号', trigger: 'blur' }]:'',
        //   placeholder: '',
        // },
        {
          type: 'INPUT',
          label: '开票客户',
          fieldName: 'invoiceCustomer',
          rules: this.type!=='show'?[{ required: true, message: '请填写开票客户', trigger: 'blur' }]:'',
          initialValue: '',
          placeholder: '',
          readonly: true,
          unitRender: () => {
            return <el-button icon="el-icon-search" onClick={this.invoiceLinkManSearch}></el-button>;
          }
        },
        {
          type: 'INPUT',
          label: '发票编号',
          fieldName: 'invoiceNo',
          rules: this.type!=='show'?[{ required: true, message: '请填写发票编号', trigger: 'blur' }]:'',
          initialValue: '',
          placeholder: '',
        },
        {
          type: 'INPUT',
          label: '发票代码',
          fieldName: 'invoiceCode',
          rules: this.type!=='show'?[{ required: true, message: '请填写发票代码', trigger: 'blur' }]:'',
          initialValue: '',
          placeholder: '',
        },
        {
          type: 'SELECT',
          label: '发票类型',
          fieldName: 'invoiceKind',
          rules: this.type!=='show'?[{ required: true, message: '请选择发票类型', trigger: 'blur' }]:'',
          initialValue: '',
          placeholder: '',
          itemList: this.createDictList('1207'),
        },
        {
          type: 'INPUT',
          label: '开票日期',
          fieldName: 'invoiceDate',
          disabled: true,
          initialValue: '',
          placeholder: '',
        },
        {
          type: 'INPUT_NUMBER',
          label: '开票金额',
          fieldName: 'invoiceAmount',
          rules: this.type!=='show'?[{ required: true, message: '请填写开票金额', trigger: 'blur' }]:'',
          initialValue: '',
          placeholder: '',
        },
        {
          type: 'SELECT',
          label: '付款方式',
          fieldName: 'payMode',
          disabled: true,
          initialValue: '',
          placeholder: '',
          itemList: this.createDictList('1426')
        },
        {
          type: 'INPUT',
          label: '成交价格',
          fieldName: 'vehiclePrice',
          disabled: true,
          initialValue: '',
          placeholder: '',
        },
        {
          type: 'INPUT',
          label: '销售顾问',
          fieldName: 'consultant',
          disabled: true,
          initialValue: '',
          placeholder: '',
        },
        {
          type: 'SELECT',
          label: '是否三包',
          fieldName: 'isInsurance',
          rules: this.type!=='show'?[{ required: true, message: '请选择', trigger: 'blur' }]:'',
          initialValue: '',
          placeholder: this.type!=='show'?'请选择':'',
          itemList: this.createDictList('1004'),
        },
        {
          type: 'UPLOAD_FILE',
          label: '上传发票',
          fieldName: 'invoiceUrl',
          selfCols: 2,
          placeholder: '上传发票...',
          style: {width: '300px'},
          disabled: this.type == 'show'? true:false,
          rules: this.type!=='show'?[{ required: true, message: '上传发票', trigger: 'blur' }]:'',
          upload: {
            actionUrl: '/api/file/oss/upload',
            limit: 1,
            tipText: '最多上传1个附件'
          }
        },
        {
          type: 'INPUT',
          label: '备注',
          fieldName: 'remark',
          selfCols: 2,
          initialValue: '',
          placeholder: '请选择',
        }
			]
    },
    saveFunc (){
      let { orginData } = this;
      this.$refs.formPanelC.SUBMIT_FORM();
      console.log('saveFunc --- before', this.saveData,this.selectCustomerId, orginData)
      if (this.saveData == null || !this.selectCustomerId) {
        return
      }
      let params = {
        invoiceAmount: Number(this.saveData.invoiceAmount), // 开票金额 must
        invoiceCode: this.saveData.invoiceCode, // 发票代码 must
        invoiceCustomer: this.saveData.invoiceCustomer, // 开票客户 must
        invoiceCustomerId: this.selectCustomerId,
        invoiceKind: this.saveData.invoiceKind, // 发票类型 must
        invoiceNo: this.saveData.invoiceNo, // 发票编号 must
        invoiceUrl: this.saveData.invoiceUrl[0].url, // 发票地址 must
        isInsurance: this.saveData.isInsurance, // 是否三包 must
        recordVersion: orginData.recordVersion, // 版本号 recordVersion
        remark: this.saveData.remark, // 备注
        soInvoiceId: orginData.soInvoiceId, // 发票Id
        soVinId: orginData.soVinId, // 客户订单车辆列表id soVinId
        transactor: this.saveData.transactor, // 开票人 // must
        viNo: orginData.viNo, // 销售订单号 viNo
        vorId: '', // 主键
        // invoiceMobile: this.saveData.invoiceMobile//'invoiceMobile' 以后版本需要
      }
      console.log(params)
      updateSalesOrderInvoice(params).then(res => {
        if (res.success) {
          notifyAction('保存成功');
          this.closeDialog('refresh');
        } else {
          notifyAction(res.errMsg, 'error');
        }
      })
    },
    closeDialog (val = ''){ //返回上层
      this.$emit('close', val);
    },
    formChangeHandle(val) {
      this.saveData = _.cloneDeep(val);
    },
    // 选择开票联系人
    invoiceLinkManSearch () {
      this.visibleCustomer = true
    },
    // 开票人信息页面返回
    closeCustomerDialog(val=false,data){
      this.visibleCustomer = false
      if (data && JSON.stringify(data)!='{}') {
        this.selectCustomerId = data['customerId']
        this.formList2.find(item => item.fieldName === 'invoiceCustomer').initialValue = data['customerName']
      }
    },
    // 日期预处理
    preDateHandler(val, formatCode='YYYY-MM-DD HH:mm:ss') {
      let resultDate = val ? moment(Number(val)).format(formatCode) : val;
      if ((resultDate == 'Invalid date' || resultDate == 'Invalid Date') && val) {
        resultDate = moment(val).format(formatCode)
      }
      return resultDate;
    },
	}

}
</script>

<style scoped="scoped" lang="less">
.upWard{
	margin-top: 15px;
	text-align: center;
}
</style>
